﻿using CPPEI.Coolzon.ServiceProxy;
using Sunboxsoft.ChanceData.ServiceProxy.MainServiceRef;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.UI.Views.EventProxies
{
    /// <summary>
    /// 重新连接服务器，连接成功之后，如果服务器的状态比客户端新，那么需要启动同步客户端视图的线程
    /// </summary>
    public class RespReconnectHandler : BaseResponseHandler<Service.Contract.RespReconnectData>
    {
        protected override void OnHandle(RemoteEventProxy remoteEventProxy, Response response,
            Service.Contract.RespReconnectData responseData)
        {
            //单域模式下，重连之后需要更新展示端本地的域信息
            if (!string.IsNullOrWhiteSpace(responseData.DomainID) && !string.Equals(UIContext.Current.ControlDomainId, responseData.DomainID))
            {
                Common.Logger.WarningToTag(Library.LogTag, "更新本地域信息,旧:{0},新{1}", UIContext.Current.ControlDomainId, responseData.DomainID);
                UIContext.Current.ControlDomainId = responseData.DomainID;
            }

            if (responseData.IsSuccess)
            {
                //如果请求的域ID为空，则只修改Proxy状态
                if (string.IsNullOrWhiteSpace(response.Header.RequestHeader.DomainId))
                {
                    UpdateProxyState(responseData);
                    return;
                }
                //重连成功之后，更新本地的主服务器信息(操作员重连时会上传本地的主服务器信息)
                if (!string.IsNullOrEmpty(responseData.MainServerIP))
                {
                    UIContext.Current.UpdateMainServer(responseData.MainServerIP, responseData.MainServerPort);

                }

                if (!string.IsNullOrEmpty(responseData.OperatorIdentity))
                {
                    UIContext.Current.OperatorIdentity = responseData.OperatorIdentity;
                }
                // 重连之后服务器上有主服务器信息，跟新本地
                Common.Logger.WarningToTag(Library.LogTag, "重新连接{0}:{1}成功,更新主服务器为{2}:{3},更新操作员为:{4}",
                    responseData.ServerIP,
                    responseData.ServerPort,
                    responseData.MainServerIP,
                    responseData.MainServerPort,
                    responseData.OperatorIdentity);

                //从主服务器上受到的视图状态才让本地同步
                if (string.Equals(responseData.MainServerIP, responseData.ServerIP)
                    && responseData.MainServerPort == responseData.ServerPort)
                {
                    // 获取本地的视图状态
                    RenderView renderView = UIContext.Current.RenderView as RenderView;
                    Coolzon.ViewState.ViewState viewState = renderView.GetViewState();
                    if (viewState == null || viewState.Age != responseData.ViewStateAge)
                    {
                        SyncViewStateThread.Start(renderView, responseData.ViewStateToken);
                    }
                }

                UpdateProxyState(responseData);
            }
            else
            {
                Common.Logger.WarningToTag(Library.LogTag, "重新连接{0}:{1}失败",
                    responseData.ServerIP,
                    responseData.ServerPort);
                // 更新proxy的状态为ConnectFailure
                for (int index = 0; index < ClientProxyManager.Instance.Proxies.Count; index++)
                {
                    MainServiceProxy proxy = ClientProxyManager.Instance.Proxies[index];
                    if (string.Equals(proxy.IP, responseData.ServerIP)
                        && proxy.Port == responseData.ServerPort)
                    {
                        proxy.State = ServiceProxyState.ReconnectFailure;
                        break;
                    }
                }
            }
        }

        private static void UpdateProxyState(Service.Contract.RespReconnectData responseData)
        {
            // 更新proxy的状态为ReconnectFinished
            for (int index = 0; index < ClientProxyManager.Instance.Proxies.Count; index++)
            {
                MainServiceProxy proxy = ClientProxyManager.Instance.Proxies[index];
                if (string.Equals(proxy.IP, responseData.ServerIP)
                    && proxy.Port == responseData.ServerPort)
                {
                    proxy.State = ServiceProxyState.ReconnectFinished;
                    break;
                }
            }
        }
    }
}
